# Reksio - Memory Map Editor
# Copyright (C) 2023 CERN
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
# In applying this licence, CERN does not waive the privileges and immunities
# granted to it by virtue of its status as an Intergovernmental Organization or
# submit itself to any jurisdiction.


from pathlib import Path
from tree import TreeView
from shutil import copy2

from ruamel.yaml import YAML
from ruamel.yaml import YAML, RoundTripDumper

import cheby.gena2cheby as gena2cheby

def load_yaml_file(filename):
    with open(filename, 'r') as f:
        yaml = YAML(typ='rt')
        yaml.preserve_quotes = True
        return yaml.load(f)


def get_submaps(root_node):
    submaps = []
    for item in root_node.walk_pre_order():
        if item.node_type == "submap":
            filename = item.get('filename', None)
            if filename is not None:
                base_path = Path(root_node.filename).parent
                submap_tree = load_yaml_file(base_path / filename)
                submap_root_node = TreeView(submap_tree, 'memory-map')
                submap_root_node.filename = base_path / filename
                submaps.append(submap_root_node)
                submaps += get_submaps(submap_root_node)
    return submaps


def backup(mem_map):
    copy2(mem_map.filename, str(mem_map.filename) + ".bak")


def save(mem_map):
    with open(mem_map.filename, "w") as f:
        yaml = YAML()
        yaml.preserve_quotes = True
        yaml.boolean_representation = ['false', 'true']
        yaml.indent(mapping=2, sequence=4, offset=2)
        yaml.width = 66666
        yaml.dump(mem_map.tree, f)


def convert_xml_to_cheby(filename: str) -> str:
    gena2cheby.flag_recurse = True
    gena2cheby.flag_out_file = True
    gena2cheby.flag_enums = True
    gena2cheby.process_file(filename)

    return str(Path(filename).with_suffix('.cheby'))

